import axios from 'axios'
import qs from 'qs'
import baseUrl from './baseUrl'
import { getCookie } from './storage'
import { Toast } from 'vant'
import router from '../router'

axios.defaults.withCredentials = true
const service = axios.create({
  baseURL: baseUrl,
  timeout: 10000
})
service.interceptors.request.use(config => {
  // loading
  const tokend = getCookie('Token')
  tokend && (config.headers.common['token'] = tokend)
  config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  return config
}, error => {
  return Promise.error(error)
})

service.interceptors.response.use(response => {
  console.log(response)
  const res = response.data
  if (res.resultCode !== 2000) {
    Toast.fail(res.resultMsg)
    // 5000 出现异常 5001授权失败
    return Promise.reject(response)
  } else {
    return Promise.resolve(response.data)
  }
}, error => {
  const errCode = error.response.data.resultCode
  if (errCode) {
    switch (errCode) {
      case 5001: // 授权失败
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        }); break
      case 3001: // 签名参数不正确
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        }); break
      default:
        Toast({
          message: error.response.data.resultMsg,
          duration: 1500,
          forbidClick: true
        })
    }
    console.log('err' + error) // for debug
    return Promise.reject(error.response)
  }
})

export default {
  post (url, data) {
    return service({
      method: 'post',
      baseURL: baseUrl,
      url,
      data: qs.stringify(data),
      timeout: 10000
    })
  },
  filepost (url, data) {
    return axios({
      method: 'post',
      baseURL: baseUrl,
      url,
      data: data,
      timeout: 10000,
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  get (url, params) {
    return axios({
      method: 'get',
      baseURL: baseUrl,
      url,
      params, // get 请求时带的参数
      timeout: 10000
    })
  }
}
